import axios from 'axios'
import { useState } from 'react'
import { useMutation, useQueryClient } from 'react-query'

async function addTodo (todo) {
  try {
    return axios.post('/todos', todo)
  } catch {
    throw new Error('添加任务失败')
  }
}

function TodosHeader () {
  const queryClient = useQueryClient()
  const [title, setTitle] = useState('')
  const { mutate } = useMutation(addTodo, {
    onSuccess () {
      setTitle('')
      // 使本地缓存中的 todos 状态无效, 重新发送请求同步状态。
      queryClient.invalidateQueries('todos')
    }
  })

  return (
    <header className='header'>
      <h1>Todos</h1>
      <input
        className='new-todo'
        placeholder='What needs to be done?'
        autoFocus
        value={title}
        onChange={event => setTitle(event.target.value)}
        onKeyUp={event => {
          if (event.code === 'Enter') {
            mutate({ title, isCompleted: false, isEditing: false })
          }
        }}
      />
    </header>
  )
}

export default TodosHeader
